import pathToRegexp from 'path-to-regexp'
import api from 'api'

const {
    queryRole
} = api

export default {
  namespace: 'role',

  state: {
    list: [],

    currentItem: {},
    modalVisible: false,
    modalType: 'create'
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if (pathToRegexp('/role/list').exec(pathname)) {
          dispatch({ type: 'query' })
        }
      })
    },
  },

  effects: {
    *query({ payload = {} }, { call, put }) {
        const data = yield call(queryRole, payload);
        if(data.success) {
          const result = data.data;
          yield put({
            type: 'setState',
            payload: {
              list: result || [],
            }
          })
        } else {
          throw data
        }
      },

    // *create({ payload }, { call, put }) {
    //   const data = yield call(saveLegal, payload)
    //   if (data.success) {
    //     yield put({ type: 'hideModal' })
    //   } else {
    //     throw data
    //   }
    // },

    // *update({ payload }, { select, call, put }) {
    //   const id = yield select(({ user }) => user.currentItem.id)
    //   const newUser = { ...payload, id }
    //   const data = yield call(updateUser, newUser)
    //   if (data.success) {
    //     yield put({ type: 'hideModal' })
    //   } else {
    //     throw data
    //   }
    // },

    // *delete({ payload }, { call, put }) {
    //   const data = yield call(deleteAdmin, { id: payload })
    //   console.log(data,76)
    //   if (data.success) {
    //     return data
    //   } else {
    //     throw data
    //   }
    // },

    
    
  },

  reducers: {
    setState(state, action) {
      return {
        ...state,
        ...action.payload,
      }
    },

    querySuccess(state, { payload }) {
      const { list, pagination } = payload
      return {
        ...state,
        list,
        pagination: {
          ...state.pagination,
          ...pagination,
        },
      }
    },

    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
}
